import { useState, useEffect, useRef } from 'react';
import { Form, Button, Input, message } from 'antd';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import BankLimitModal from '../../../../common/BanKLimitModal';
import AddAuthentication from '../../../../common/AddAuthentication';
import {
  queryClassIIBindCardOp,
  applySignUpgradeOp,
  signValidOp,
  rechargeOptOp,
  rechargeValidOp,
} from '../../../service';
import styles from './index.module.less';

export const layout = {
  labelCol: {
    span: 7,
  },
  wrapperCol: {
    span: 16,
  },
};

const reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/; //提现金额正则

let timer;

const BalanceRechargeModal = ({
  isSign,
  accountExtend,
  userAccountType,
  getAuthenticationInfo,
  handleOk,
  handleCancel,
}) => {
  const [form] = Form.useForm();

  const [loading, setLoading] = useState(false);
  const [step, setStep] = useState(1);
  const [accountInfo, setAccountInfo] = useState({});
  const [visible, setVisible] = useState(false);
  const [authenticationVisible, setAuthenticationVisible] = useState(false); // 认证的visible
  const [isUpgrade, setIsUpgrade] = useState(false); //是否是升级

  const [countDown, setCount] = useState(0);

  const stageData = useRef({});

  const {
    accountNo,
    bankNo,
    mobile,
    name,
    openBankName,
    limitAmount,
    oneMoney,
  } = accountInfo;

  useEffect(() => {
    setStep(isSign ? 1 : 2);
    queryClassIIBindCard();
  }, []);

  useEffect(() => {
    if (countDown) {
      timer = setTimeout(() => {
        setCount(countDown - 1);
      }, 1000);
    }
  }, [countDown]);

  const queryClassIIBindCard = async () => {
    setLoading(true);
    const { data, success } = await queryClassIIBindCardOp();
    if (success) {
      setAccountInfo(data || {});
      if (step == 1) {
        form.setFieldsValue({ mobile: data?.mobile });
      }
    }
    setLoading(false);
  };

  //获取验证码,并开始倒计时
  const handleGetCode = async () => {
    let res;
    setLoading(true);
    if (step == 1) {
      res = await applySignUpgradeOp({ bankNo });
    } else {
      await form
        .validateFields(['payAmount'])
        .then(async (value) => {
          const { payAmount } = value;
          res = await rechargeOptOp({
            accountNo,
            payAmount: payAmount - 0,
            orderSrc: 7,
          });
        })
        .catch((err) => setLoading(false));
    }
    if (res?.success) {
      stageData.current = { ...stageData.current, ...res?.data };
      // console.log(stageData.current,'current');
      setCount(59);
      message.success('验证码发送成功!');
    }
    setLoading(false);
  };

  //确认签约
  const signOK = async () => {
    form.validateFields(['otpValue']).then(async (value) => {
      setLoading(true);
      const { otpValue } = value;
      const { signId } = stageData.current;
      const { success, msg } = await signValidOp({
        accountNo,
        otpValue,
        signId,
      });
      if (success) {
        clearTimeout(timer);
        setCount(0);
        setStep(2);
        stageData.current.isSigned = true;
        message.success(msg);
      }
      setLoading(false);
    });
  };

  //确认充值
  const rechargeOK = async () => {
    form.validateFields().then(async (value) => {
      setLoading(true);
      const { otpValue } = value;
      const { otpOrderNo, payOrderSn } = stageData.current;
      const { success, msg } = await rechargeValidOp({
        accountNo,
        otpValue,
        otpOrderNo,
        payOrderSn,
      });
      if (success) {
        setCount(0);
        handleOk();
        message.success(msg);
      }
      setLoading(false);
    });
  };

  const onBlur = () => {
    form.setFieldsValue({ otpValue: null });
  };

  //签约成功后需要更新账户相关信息
  const onCancel = () => {
    if (stageData.current.isSigned) {
      handleOk();
    } else {
      handleCancel();
    }
  };

  //点击升级认证
  const handleUpgrade = () => {
    setAuthenticationVisible(true);
    setIsUpgrade(true);
  };

  const renderFooter = () => {
    if (step == 1) {
      return (
        <>
          <Button onClick={handleCancel}>取消</Button>
          <Button type="primary" onClick={signOK}>
            确定
          </Button>
        </>
      );
    } else if (step == 2) {
      return (
        <>
          <Button onClick={onCancel}>取消</Button>
          <Button type="primary" onClick={rechargeOK}>
            确认充值
          </Button>
        </>
      );
    }
  };

  //修改认证/升级企业认证
  const AddAuthenticationProps = {
    visible: authenticationVisible,
    accountExtend,
    userAccountType,
    isUpgrade,
    handleCancel() {
      setAuthenticationVisible(false);
    },
    handleOk() {
      setAuthenticationVisible(false);
      getAuthenticationInfo();
    },
  };

  return (
    <CommonModal
      title={step == 1 ? '温馨提示' : '余额充值'}
      visible={true}
      onCancel={handleCancel}
      footer={renderFooter()}
    >
      {step == 1 && (
        <>
          <p style={{ fontSize: '15px', padding: '6px 0 8px 16px' }}>
            首次充值，该银行卡需要进行二次认证
          </p>
          <Form
            name="second-account-balance-recharge-form"
            form={form}
            {...layout}
          >
            <Form.Item label="手机号" name="mobile" disabled>
              <Input disabled />
            </Form.Item>

            <Form.Item
              label="手机验证码"
              name="otpValue"
              rules={[{ required: true, message: '请输入手机验证码' }]}
            >
              <div className="flex">
                <Input />
                <Button
                  style={{ marginLeft: 24 }}
                  onClick={handleGetCode}
                  disabled={countDown}
                >
                  获取验证码{countDown ? `(${countDown})` : ''}
                </Button>
              </div>
            </Form.Item>
          </Form>
        </>
      )}

      {step == 2 && (
        <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
          <div className={styles.showContent}>
            <p>
              <span>开户银行</span>：{openBankName}
            </p>
            <p>
              <span>银行卡号</span>：{bankNo}
            </p>
            <p>
              <span>开户人姓名</span>：{name}
            </p>
            <p>
              <span>手机号</span>：{mobile}
            </p>
            <p>
              <span>充值限额</span>：{limitAmount ? limitAmount : '-'}/每笔，
              {oneMoney ? oneMoney : '-'}/每日
            </p>
          </div>
          <div style={{ padding: '6px 30px 8px 40px' }}>
            此次操作将会从您绑定的上述银行卡里扣钱充值到账户，请确保卡里余额充足!
          </div>
          <Form.Item
            label={<div className="lable-require">充值金额</div>}
            name="payAmount"
            rules={[
              () => ({
                validator(rule, value) {
                  if (!value) {
                    return Promise.reject(`请输入充值金额`);
                  } else if (!reg.test(value)) {
                    return Promise.reject(`请正确输入充值金额,最多两位小数`);
                  } else if (value - 0 < 2) {
                    return Promise.reject(`金额不能小于2元`);
                  }
                  return Promise.resolve();
                },
              }),
            ]}
          >
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                height: '28px',
              }}
            >
              <Input
                style={{ width: '200px' }}
                placeholder="起充金额2元，请输入金额"
                suffix="元"
                onBlur={onBlur}
              />
              &nbsp;&nbsp;&nbsp;&nbsp;
              {accountExtend?.accountType == 1 ? (
                <Button onClick={() => handleUpgrade()}>升级为企业认证</Button>
              ) : (
                ''
              )}
              {/* <span className='common-color2' onClick={() => setVisible(1)}>查看支持银行和充值限额</span> */}
            </div>
          </Form.Item>

          <Form.Item
            label="验证码"
            name="otpValue"
            rules={[{ required: true, message: '请输入验证码' }]}
            style={{ marginTop: '28px' }}
          >
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <Input placeholder="请输入验证码" />
              &nbsp;&nbsp;&nbsp;&nbsp;
              <Button onClick={handleGetCode} disabled={countDown}>
                获取验证码{countDown ? `(${countDown})` : ''}
              </Button>
            </div>
          </Form.Item>
        </Form>
      )}
      <BankLimitModal
        visible={visible == 1}
        handleClose={() => setVisible(false)}
      />
      {/* 实名认证 */}
      {authenticationVisible && (
        <AddAuthentication {...AddAuthenticationProps} />
      )}
      <CommonLoading loading={loading} />
    </CommonModal>
  );
};

export default BalanceRechargeModal;
